package com.kzw.oa.system.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kzw.core.bean.Msg;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.json.JSON;
import com.kzw.core.util.web.ResponseUtils;
import com.kzw.oa.system.model.AppUser;
import com.kzw.oa.system.model.Department;
import com.kzw.oa.system.model.UserOrg;
import com.kzw.oa.system.service.AppUserService;
import com.kzw.oa.system.service.DepartmentService;
import com.kzw.oa.system.service.UserOrgService;

@Controller
@RequestMapping("/system/userOrg")
public class UserOrgAction {

	@Autowired
	private AppUserService appUserService;
	@Autowired
	private DepartmentService deptService;
	@Autowired
	private UserOrgService userOrgService;

	/**
	 * 查找某一用户所有的部门列表
	 */
	@RequestMapping("find")
	public void find(String userId, HttpServletResponse response) {
		String json;
		if (StringUtils.isNotEmpty(userId)) {
			List<UserOrg> userOrgs = userOrgService.getDepOrgsByUserId(new Long(userId));
			StringBuffer sb = new StringBuffer("{success:true,result:[");
			for (UserOrg userOrg : userOrgs) {
				sb.append("{userOrgId:'").append(userOrg.getUserOrgId()).append("',orgId:'")
						.append(userOrg.getDept().getDepId()).append("',orgName:'")
						.append(userOrg.getDept().getDepName()).append("',isPrimary:'").append(userOrg.getIsPrimary());
				Short isCharge = userOrg.getIsCharge() == null ? 0 : userOrg.getIsCharge();
				sb.append("',isCharge:'").append(isCharge);
				sb.append("'},");
			}
			if (userOrgs.size() > 0) {
				sb.deleteCharAt(sb.length() - 1);
			}
			sb.append("]}");
			json = sb.toString();
		} else {
			json = "{success:true,result[]}";
		}
		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 为某此用户添加所属组织或部门
	 */
	@RequestMapping("addOrgs")
	@ResponseBody
	public Msg addOrgs(String userIds, String orgId) {
		if (StringUtils.isNotEmpty(userIds)) {
			String[] uIds = userIds.split("[,]");
			Department org = deptService.get(new Long(orgId));
			for (String id : uIds) {
				List<UserOrg> userOrgs = userOrgService.getByUserIdOrgId(new Long(id), new Long(orgId));
				if (userOrgs.size() == 0) {
					UserOrg userOrg = new UserOrg();
					AppUser user = appUserService.get(new Long(id));
					userOrg.setAppUser(user);
					userOrg.setDept(org);
					userOrg.setIsPrimary(UserOrg.NOT_PRIMARY);
					userOrg.setIsCharge(UserOrg.NOT_CHARGE);
					userOrgService.saveOrUpdate(userOrg);
				}
			}
		}
		return new Msg(true);
	}

	/**
	 * 显示列表
	 */
	@RequestMapping("list")
	public void list(HttpServletRequest request, HttpServletResponse response) {

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);

		Page<UserOrg> page = userOrgService.search2(pageRequest, filters);
		String json = new JSON(page).buildWithFilters(3);

		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 批量删除
	 */
	@RequestMapping("multiDel")
	@ResponseBody
	public Msg multiDel(String ids, Long orgId) {

		String[] userIds = ids.split(",");
		for (String uid : userIds) {
			if (uid.length() > 0) {
				userOrgService.delCascade(new Long(uid), orgId);
			}
		}
		return new Msg(true);
	}

	/**
	 * 显示详细信息
	 */
	@RequestMapping("get")
	public void get(Long userOrgId, HttpServletResponse response) {
		UserOrg userOrg = userOrgService.get(userOrgId);

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		// 将数据转成JSON格式
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(gson.toJson(userOrg));
		sb.append("}");

		ResponseUtils.renderJson(response, sb.toString());
	}

	/**
	 * 添加及保存操作
	 */
	@RequestMapping("save")
	@ResponseBody
	public Msg save(UserOrg userOrg) {
		if (userOrg.getUserOrgId() == null) {
			userOrgService.saveOrUpdate(userOrg);
		} else {
			UserOrg orgUserOrg = userOrgService.get(userOrg.getUserOrgId());
			try {
				BeanUtil.copyNotNullProperties(orgUserOrg, userOrg);
				userOrgService.saveOrUpdate(orgUserOrg);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return new Msg(true);

	}

	/**
	 * 删除对应的用户组织
	 */
	@RequestMapping("del")
	@ResponseBody
	public Msg del(Long userOrgId) {
		if (userOrgId != null) {
			userOrgService.remove(userOrgId);
		}
		return new Msg(true);
	}
}
